import logging
import os
import datetime


class UserLog(object):
    abs_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    config_format = '%(levelname)s %(thread)s %(asctime)s %(filename)s %(funcName)s() ' \
                    '[%(lineno)d]  --> %(message)s'
    data_fmt = '%H:%M:%S'

    def __init__(self):
        self.logger1 = logging.getLogger(__name__)
        logging.Logger.manager.loggerDict.pop(__name__)
        self.logger1.handlers = []
        self.logger1.removeHandler(self.logger1.handlers)
        if not self.logger1.handlers:
            self.logger1.setLevel(logging.DEBUG)
            # 控制台输出日志
            # console = logging.StreamHandler()
            # logger.addHandler(consle)
            log_dir = self.abs_dir + '\\'
            log_file = datetime.datetime.now().strftime("%Y-%m-%d") + ".log"
            log_name = os.path.join(log_dir + log_file)
            # print(log_name)
            # a_base_dir = os.path.dirname(base_dir)
            # print(base_dir);print(a_base_dir)
            # 文件输出日志
            self.file_handle = logging.FileHandler(log_name, 'w', encoding='utf-8')
            self.file_handle.setLevel(logging.DEBUG)
            formatter = logging.Formatter(self.config_format, datefmt=self.data_fmt)
            self.file_handle.setFormatter(formatter)
            self.logger1.addHandler(self.file_handle)

    def main(self):
        return self.logger1

    def close_handle(self):
        self.main().debug('关闭日志模块')
        self.logger1.removeHandler(self.file_handle)
        self.file_handle.close()
    # def __del__(self):
    # 会报错
    #     self.close_handle()
    #     del self


user_log = UserLog()
log = user_log.main()
log.close = user_log.close_handle
if __name__ == '__main__':
    user = user_log
    log.debug('test')
    log.close()
    # user.close_handle()
